package cn.itcast.store.service.serviceImp;

import java.sql.Connection;
import java.util.List;

import cn.itcast.store.dao.OrderDao;
import cn.itcast.store.dao.daoImp.OrderDaoImp;
import cn.itcast.store.domain.Order;
import cn.itcast.store.domain.OrderItem;
import cn.itcast.store.domain.PageModel;
import cn.itcast.store.domain.User;
import cn.itcast.store.service.OrderService;
import cn.itcast.store.utils.JDBCUtils;

public class OrderServiceImp implements OrderService {

	@Override
	public void saveOrder(Order order) throws Exception {
		OrderDao OrderDao = new OrderDaoImp();
		Connection conn = null;
		try {
			// 获取连接
			conn = JDBCUtils.getConnection();
			// 开启事务
			conn.setAutoCommit(false);
			// 保存订单

			OrderDao.saveOrder(conn, order);
			// 保存订单项

			for (OrderItem item : order.getList()) {

				OrderDao.saveOrderItem(conn, item);
			}
			// 提交
			conn.commit();
		} catch (Exception e) {
			// 回滚
			conn.rollback();
		}

	}

	@Override
	public PageModel findMyOrdersWithPage(User user, int num) throws Exception {
		OrderDao OrderDao = new OrderDaoImp();
		int totalRecords = OrderDao.getTotalRecords(user);
		
		PageModel pm = new PageModel(num, totalRecords, 3);
		
		List list = OrderDao.findMyOrdersWithPage(user, pm.getStartIndex(), pm.getPageSize());
		
		pm.setList(list);
		pm.setUrl("OrderServlet?method=findMyOrdersWithPage");
		return pm;
	}

	@Override
	public Order findOrderByOid(String oid) throws Exception {
		OrderDao OrderDao = new OrderDaoImp();
		return OrderDao.findOrderByOid(oid);
	}

	@Override
	public void updateOrder(Order order) throws Exception {
		OrderDao OrderDao = new OrderDaoImp();
		OrderDao.updateOrder(order);
		
	}

	@Override
	public List<Order> findOrderS() throws Exception{
		OrderDao OrderDao = new OrderDaoImp();
		System.out.println("111111111111"+OrderDao.findOrderS());
		return OrderDao.findOrderS();
	}

	@Override
	public List<Order> findOrderS(String state) throws Exception{
		OrderDao OrderDao = new OrderDaoImp();
		System.out.println(OrderDao.findOrderS(state));
		return OrderDao.findOrderS(state);
	}

}
